//
//  BLSquare.m
//  百思不得姐
//
//  Created by hbl on 16/3/30.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "BLSquare.h"
#import "BLNetwork.h"
#import "MJExtension.h"
#import "BLSquareModel.h"
#import "BLSquareButton.h"
#import "UIButton+WebCache.h"
#import "BLWebViewController.h"
@interface BLSquare ()
@property (nonatomic, strong)NSArray *squareData;

@end

@implementation BLSquare

- (NSArray *)squareData{
    if (!_squareData) {
        _squareData = [[NSArray alloc]init];
    }
    return _squareData;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"square";
        params[@"c"] = @"topic";
        
        [BLNetwork GET:@"http://api.budejie.com/api/api_open.php" parameter:params success:^(id result) {
        
            self.squareData = [BLSquareModel mj_objectArrayWithKeyValuesArray:result[@"square_list"]];
            [self createSquare:self.squareData];
        } failure:^(NSError *error) {
            
        }];
    }
    return self;
}

- (void)createSquare:(NSArray *)data
{
    int maxColum = 4;
    CGFloat btnW = mainW/maxColum;
    CGFloat btnH = btnW;
    int index = 0;
    for (int i = 0; i< data.count;i++ ) {
        BLSquareModel *squareModel = data[i];
        if ([squareModel.url hasPrefix:@"http"]) {
            BLSquareButton *btn = [[BLSquareButton alloc]init];
            [btn setTitle:squareModel.name forState:UIControlStateNormal];
            [btn sd_setImageWithURL:[NSURL URLWithString:squareModel.icon] forState:UIControlStateNormal];
            btn.url = squareModel.url;
            CGFloat btnX = index%4 * btnW;
            CGFloat btnY = index/4 * btnH;
            [btn setBackgroundImage:[UIImage imageNamed:@"mainCellBackground"] forState:UIControlStateNormal];
            btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
            
            [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:btn];
            index ++;
        }
        
    }
    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, (index + maxColum - 1)/maxColum * btnH);

}


- (void)onClick:(BLSquareButton *)btn
{
    
    UITabBarController *barVc= (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = (UINavigationController *)barVc.selectedViewController;
    BLWebViewController *webVc = [[BLWebViewController alloc]init];
    webVc.url = btn.url;
    [nav pushViewController:webVc animated:YES];
}
//- (void)drawRect:(CGRect)rect {
//    // Drawing code
//    [[UIImage imageNamed:@"bg_media_default"] drawInRect:CGRectMake(0, 90, 300, 300)];
//    
//}


@end
